<?php

namespace app\admin\controller\shop;

use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use app\common\model\Admin;
use app\common\model\Category;
use app\common\model\CategoryInfo;
use app\common\model\shop\Goods as ShopGoods;
use app\common\model\shop\goods\Acct;
use app\common\model\shop\goods\User;
use Exception;
use Jdy;
use PDOException;
use think\Db;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\common\model\shop\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\shop\Goods;
        $this->view->assign("saleSwitchList", $this->model->getSaleSwitchList());
        $uids = AuthGroupAccess::where('group_id', 10)->column('uid');
        $this->assignconfig("adminList", Admin::where('id', 'in', $uids)->column('acct_id,nickname'));
        $this->assignconfig("acct_visible", $this->auth->acct_id == 0 ? true : false);
        $this->view->assign("acct_id", $this->auth->acct_id);
        $this->assignconfig("price_visible", $this->auth->acct_id == 0 ? false : true);
        $this->assignconfig("admin", $this->auth->getUserInfo());
        $category = new Category();
        if ($this->auth->acct_id > 0) {
            $ids = CategoryInfo::where('acct_id', $this->auth->acct_id)->column('category_id');
            $category->whereIn('id', $ids);
        }
        $categorylist =  $category->where('type', 'goods')->select();
        $this->view->assign("categorylist", $categorylist);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['category','first'])
                ->where($where)
                ->where('custom', 0)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('first')->visible(['name', 'image']);
                $row->getRelation('category')->visible(['name', 'image']);
                // $row->acct = Acct::where('goods_id', $row['id'])->where('acct_id', $this->auth->acct_id)->find();
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            // if (!$params['acct_json']) {
            //     exception('请添加授权平台');
            // }
            // $acct_array =  json_decode($params['acct_json'], true);
            // $acct_ids = array_column($acct_array, 'acct_id');
            // $params['acct_ids'] = implode(',', $acct_ids);
            $result = $this->model->allowField(true)->save($params);
            // if ($result) {
            //     foreach ($acct_array as $k => $v) {
            //         $data = [
            //             'goods_id' => $this->model->id,
            //             'acct_id' => $v['acct_id'],
            //             'purchase_price' => $v['purchase_price'],
            //             'price' => $v['price'],
            //         ];
            //         Acct::create($data);
            //     }
            // }

            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            // if (!$params['acct_json']) {
            //     exception('请添加授权平台');
            // }
            // $accts = Acct::all(['goods_id' => $ids]);
            // $acct_array =  json_decode($params['acct_json'], true);
            // $idss = array_column($acct_array, 'id');
            // $acct_ids = array_column($acct_array, 'acct_id');
            // foreach ($accts as $k => $v) {
            //     if (!in_array($v->id, $idss)) {
            //         $v->delete();
            //     }
            // }
            // $params['acct_ids'] = implode(',', $acct_ids);

            // foreach ($acct_array as $k => $v) {

            //     $data = [
            //         'goods_id' => $ids,
            //         'acct_id' => $v['acct_id'],
            //         'purchase_price' => $v['purchase_price'],
            //         'price' => $v['price'],
            //     ];
            //     $check = Acct::get($data);
            //     if ($check) {
            //         continue;
            //     }
            //     $option = Acct::get($v['id']);
            //     if ($option) {
            //         $option->save($data);
            //     } else {
            //         Acct::create($data);
            //     }
            // }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 导入
     */
    public function import($ids = null)
    {
        // $pg = $this->model->get($ids);
        // $this->view->assign("row", $pg);
        // $row = 
        if ($this->request->isPost()) {
            $msg = '';

            $file = $this->request->request('idata');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }



            $fieldArr = [
                'Id' => 'id',
                // '好有才商品CODE' => 'product_code',
                '金蝶编号' => 'jdy_num',

            ];
            $insert = [];
            // Db::startTrans();
            try {
                $api = new Jdy();

                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error(__('Unknown data format'));
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $fields[] = $val;
                    }
                }

                $i = 1;
                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = [];
                    $temp = array_combine($fields, $values);

                    foreach ($temp as $k => $v) {
                        // var_dump($k);var_dump($v);die;
                        if (isset($fieldArr[$k]) && $k !== '') {
                            // ltrim($v,'`');
                            $row[$fieldArr[$k]] = ltrim($v, '`');
                        }
                    }
                    if ($row) {

                        // $row['admin_id'] = $pg['admin_id'];
                        // $row['kl_num'] = $row['kl_num'] ?? $row['out_num'];
                        // $row['pg_id'] = $ids;
                        // $row['no'] = $row['no'] ?? $row['s_no'];
                        // $row['c_no'] = date('Ymd') . $row['no'];
                        // $row['c_no'] = date('Ymd').'-'.$ids.'-'.($currentRow-1).'-'.$row['no'];
                        // $row['true_el'] = floatval($row['true_el'] ?? 0);
                        // $row['top_el']  = floatval($row['top_el'] ?? 0);
                        // $row['normal_el'] = floatval($row['normal_el'] ?? 0);
                        // $row['low_el'] = floatval($row['low_el'] ?? 0);
                        if ($row['jdy_num']) {
                            $goods = ShopGoods::get($row['id']);
                            if ($goods && $goods['jdy_num'] != $row['jdy_num']) {
                                $a = $api->getGoods($row['jdy_num']);
                                if ($a) {
                                    // $row['jdy_id'] = $a;
                                    $goods->jdy_id = $a;
                                    $goods->jdy_num = $row['jdy_num'];
                                    $goods->save();
                                }
                            }

                            // if ($a) {
                            //     $row['jdy_id'] = $a;
                            // }
                            // $insert[] = $row;
                        }
                        $i++;
                    }
                }

                // $this->model->saveAll($insert);


                // Db::commit();
            } catch (PDOException $e) {
                // Db::rollback();
                // dump($e);
                $this->error('操作失败:异常' . $e->getMessage() . '');
                // Db::commit();

            } catch (Exception $e) {
                // dump($e);

                // dump($e->getMessage());
                // dump($e->getLine());
                // dump($e->getFile());


                // Db::rollback();
                $this->error($e->getMessage());
            }
            if ($msg) {
                $this->error($msg);
            }



            //删除导入文件
            @unlink($filePath);
            $this->success();
        }

        return $this->view->fetch();
    }


    function exportExcel($fileName = '商品列表', $title = [], $data = [], $sheetName = null, $type = null)
    {
        set_time_limit(0);
        // $search = $this->request->post('search');
        $ids = $this->request->post('ids');
        // $filter = $this->request->post('filter');
        // $op = $this->request->post('op');
        $title = ['Id', '商品名', '分类', '规格', '金蝶编号', '金蝶ID'];
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        if (isset($sheetName) && !empty($sheetName)) {
            $sheet->setTitle($sheetName);
        } else {
            $sheet->setTitle(date('Y-m-d', time()));
        }
        // $sheet->getDefaultColumnDimension()->setWidth(40);
        $iRow = 0;
        //设置单元格内容
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
            $iRow = $iRow + 1;
            $colum = self::index2ColName($iRow);
            $sheet->getColumnDimension($colum)->setAutoSize(true);
            //设置单元格宽度  与setAutoSize 是冲突的
            //$sheet->getDefaultColumnDimension()->setWidth(20);
            //$sheet->getColumnDimension('B')->setWidth(50);
            $sheet->getStyle($colum . '1')->getFont()->setBold(true);
        }

        $data = collection($this->model->with(['category'])->select())->toArray();
        // collection($this->model->where('order_status', 10)->column('contact,telephone,address'))->toArray();
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $column = 1;
            $arr = [$item['id'], $item['title'], $item['category']['name'] ?? '', $item['intro'], $item['jdy_num'], $item['jdy_id']];
            foreach ($arr as $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }
        if (isset($type)) {
            # 保存为xlsx
            $fileName = $fileName . '.Xlsx';
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $filePath = ROOT_PATH . 'public/uploads/excel/' . $fileName;
            $writer->save($filePath);
            return $filePath;
            die;
        } else {
            # 浏览器下载
            $fileName = $fileName . '.xlsx';
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            ob_end_clean();
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            $writer->save('php://output');
            //删除清空
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
            exit;
        }
    }
    //根据列数转Excel的列名；
    static function index2ColName($columnNumber)
    {
        $dividend = $columnNumber;
        $columnName = '';
        while ($dividend > 0) {
            $modulo = ($dividend - 1) % 26;
            $columnName = chr(65 + $modulo) . $columnName;
            $dividend = (int)(($dividend - $modulo) / 26);
        }
        return $columnName;
    }
}
